﻿using DataBase.Utils;
using GreenXi.Model;
using GreenXi.Pages.index;
using Prism.Commands;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using static GreenXi.App;
using static GreenXi.ViewModel.LoginViewModel;

namespace GreenXi.ViewModel
{

    public class SelectUserViewModel : INotifyPropertyChanged
    {
        //日志
        private readonly ILogger logger;

        #region 页面元素
        //表格内容
        private ObservableCollection<User>? _userList;
        public ObservableCollection<User>? UserList
        {
            get { return _userList; }
            set { _userList = value; OnPropertyChanged(nameof(UserList)); }
        }
        public List<string>? RoleGroupList { get; set; }
        //当前选择的内容
        private User? _selectUser;
        public User? SelectUser
        {
            get { return _selectUser; }
            set
            {
                if (_selectUser != value)
                {
                    _selectUser = value;
                    OnPropertyChanged(nameof(SelectUser));
                }
            }
        }
        //保存按钮绑定的指令
        public ICommand ChangeUserCommand { get; }
        public ICommand RefreshCommand { get; }
        #endregion

        #region 数据初始化 
        public SelectUserViewModel()
        {
            UpdateInfo();
            ChangeUserCommand = new DelegateCommand(() => ChangeUser(SelectUser));
            RefreshCommand = new DelegateCommand(() => UpdateInfo());
            logger = new LoggerConfiguration().CreateLogger();
        }

        //更新表格内容
        public void UpdateInfo()
        {
            //获取小于等于当前登录用户权重的用户信息
            var users = CurrentUser.GetUserInfoByCurrentUserWeight();

            //将获取到的用户信息转换为User对象，并添加到 UserList 中
            UserList = new ObservableCollection<User>(users.Select(x => new User()
            {
                ID = x.UserID,
                UserName = x.UserName,
                CreatedTime = x.CreatedTime,
                Remark = x.Remark,
                RoleGroup = GetPermissionCode(x.UserName) ?? "", // 使用安全导航运算符和空合并运算符处理可能的null值
                IsEnabled = 1
            }));
            OnPropertyChanged(nameof(UserList));
            RoleGroupList = CurrentUser.GetRoleGroupList();
        }

        //获取用户的PermissionCode
        public static string GetPermissionCode(string userName)
        {
            string res = "";
            int userId = MyDbContext.Instance.Users
                .Where(x => x.UserName == userName)
                .Select(x => x.UserID)
                .FirstOrDefault();

            int? roleId = MyDbContext.Instance.UserRoleRelations
                .Where(x => x.UserId == userId)
                .Select(x => (int?)x.RoleId)
                .FirstOrDefault();

            res = MyDbContext.Instance.RolePermissions
                .FirstOrDefault(x => x.RoleID == roleId)
                ?.PermissionCode ?? "PermissionCode没找到";
            return res;
        }

        private void ChangeUser(User SelectUser)
        {
            try
            {
                //考虑没有选中对象的情况
                if (SelectUser != null)
                {
                    ChangeUserDialog changeUserDialog = new ChangeUserDialog();

                    if (changeUserDialog.ShowDialog() == true)
                    {
                        var pwd = changeUserDialog.pwd.Password ?? "";
                        LoginViewModel loginViewModel = new();
                        LoginStatus loginStatus = loginViewModel.LoginCheck(SelectUser.UserName, pwd);
                        switch (loginStatus)
                        {
                            case LoginStatus.Success:
                                break;
                            case LoginStatus.Error:
                                MessageBox.Show("密码错误！");
                                break;
                            case LoginStatus.UsernameDoesNotExist:
                                MessageBox.Show("用户名不存在！");
                                break;
                            case LoginStatus.MultipleAccounts:
                                MessageBox.Show("用户名存在多个，请联系管理员！");
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("切换登录失败！");
                // 记录错误日志
                logger.Error(ex, "切换登录操作异常：");
            }
        }
        #endregion

        #region 数据同步
        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

    }

}


